<?php

namespace App\Http\Controllers\API;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;
use Illuminate\Http\JsonResponse;
use App\Services\AliService;
use App\Repositories\DeviceRepository;


class TianmaoAPIController extends Controller
{
    private $deviceRepository;
    private $server;
    private $header;//阿里语音请求头部，协议解析
    private $payload;

    public function __construct(Request $request)
    {
        $this->deviceRepository = app(DeviceRepository::class);
        $this->server = new AliService();

    }

    public function control(Request $request)
    {
        Log::info($request->input());
        $input = $request->input();
        $this->header = $input['header'];
        $this->payload = $input['payload'];

        //设备发现
        if ($this->header['name'] == "DiscoveryDevices") {
            return $this->handleDiscoveryDevices($request);
        }

        if ($this->header['name'] == "TurnOn") {
            return $this->handleTurnOnDevices($request);
        }

        if ($this->header['name'] == "TurnOff") {
            return $this->handleTurnOffDevices($request);
        }

        if ($this->header['name'] == "SelectChannel") {
            return $this->handleSelectChannelDevices($request);
        }
        if ($this->header['name'] == "AdjustUpChannel") {
            return $this->handleAdjustUpChannelDevices($request);
        }
        if ($this->header['name'] == "AdjustDownChannel") {
            return $this->handleAdjustDownChannelDevices($request);
        }
        if ($this->header['name'] == "AdjustUpVolume") {
            return $this->handleAdjustUpVolumeDevices($request);
        }
        if ($this->header['name'] == "AdjustDownVolume") {
            return $this->handleAdjustDownVolumeDevices($request);
        }
        if ($this->header['name'] == "SetVolume") {
            return $this->handleSetVolumeDevices($request);
        }
        if ($this->header['name'] == "SetMute") {
            return $this->handleSetMuteDevices($request);
        }
        if ($this->header['name'] == "CancelMute") {
            return $this->handleCancelMuteDevices($request);
        }
        if ($this->header['name'] == "Play") {
            return $this->handlePlayDevices($request);
        }
        if ($this->header['name'] == "Pause") {
            return $this->handlePauseDevices($request);
        }
        if ($this->header['name'] == "Continue") {
            return $this->handleContinueDevices($request);
        }
        if ($this->header['name'] == "Next") {
            return $this->handleNextDevices($request);
        }
        if ($this->header['name'] == "Previous") {
            return $this->handlePreviousDevices($request);
        }
        if ($this->header['name'] == "SetBrightness") {
            return $this->handleSetBrightnessDevices($request);
        }
        if ($this->header['name'] == "AdjustUpBrightness") {
            return $this->handleAdjustUpBrightnessDevices($request);
        }
        if ($this->header['name'] == "AdjustDownBrightness") {
            return $this->handleAdjustDownBrightnessDevices($request);
        }


        if ($this->header['name'] == "SetTemperature") {
            return $this->handleSetTemperatureDevices($request);
        }
        if ($this->header['name'] == "AdjustUpTemperature") {
            return $this->handleAdjustUpTemperatureDevices($request);
        }
        if ($this->header['name'] == "AdjustDownTemperature") {
            return $this->handleAdjustDownTemperatureDevices($request);
        }
        if ($this->header['name'] == "SetWindSpeed") {
            return $this->handleSetWindSpeedDevices($request);
        }
        if ($this->header['name'] == "AdjustUpWindSpeed") {
            return $this->handleAdjustUpWindSpeedDevices($request);
        }
        if ($this->header['name'] == "AdjustDownWindSpeed") {
            return $this->handleAdjustDownWindSpeedDevices($request);
        }
    }

    public function token(Request $request)
    {
//        $rr = '{"token_type":"Bearer","expires_in":1296000,"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImFlMzY1MzNlMzg3YzJiN2VhZDY5NDdkYTVjOGZmNzVjM2IyZjlhNGI5OWE3ZTU2ODQzNjVhYmZjNWMyMjQ2NjhiYzA1Zjc5NDQ3MGY4NDA0In0.eyJhdWQiOiIzIiwianRpIjoiYWUzNjUzM2UzODdjMmI3ZWFkNjk0N2RhNWM4ZmY3NWMzYjJmOWE0Yjk5YTdlNTY4NDM2NWFiZmM1YzIyNDY2OGJjMDVmNzk0NDcwZjg0MDQiLCJpYXQiOjE1MTYyNzExNTMsIm5iZiI6MTUxNjI3MTE1MywiZXhwIjoxNTE3NTY3MTUzLCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.RXsIPE7CHAJFZvGaUymdPGXooZZo2MQFlxgn0FqhwJ2HWPkZWUeSNejlfdfBbU_2OP0PC7bYw-6R65P2RuRk_sq9tzfitguDJxcSkdzKY2rEdBQy6F_YfGWxMZPUnS1K6mcV7dCafZKmhTnWHJq5MsDhfGP7DX6y_Id4Ijsvzj8pbY2Cgrkqj2H8MFVPE32A_NHurerkNPHUVPE5ffZ0eLluVQ19e-G0H5pUPgsfQujUMT1hOzb2jTqGMQPdycC7VpBJR9_gOR0qAYp28uZC5wqEexiiWhjPA93gb_IUV3m08Zt_r2bQDZA3nKfoWOomNX8S7Mxlua_nAAeLlQT2pnqtb5pW39t5a8-DcAjbXiOoHVqv-ftA7Y1f7lQzmCZSFoliHQuqZezwmr729hCUPcqjsxlCVlCviAguAoKC6OMeugWQq1aYxcjG-m9krs70mbTkn4qhU3NBGWy1Tg2Vg3qg_dHb9l3kjxs4yAIbsDEXp3IzeJKhz3Khy5hK3iR0tSJMWepA209hXIcBkHfjLyQR7sryDmovr_emF14w-aLWTwXTFxIad5G_j5dlKnHmYfcDOapYv-G_5VcM4vddfxTyR56Oiw6YdmY4gjoz3q5ajLzvWTdi6Ecf8V6K-kyu2uTe6-M_LGE1uh__9U04uJdMSRKcfGqd_055h4UHuhE","refresh_token":"def50200121b0add77715e2f8e8386ffe26d47f14a6de1e46c1400e017168a800c1ba85c4390d1689208abfbc72a501e4e6dce6ce7a9476edb827ad91ed5ae3d383a37d8d1b4b020a2f588ace293a64de414c9da175a9923eaa14aef09ec1549f41c3a5c99e0d6cf56029de13cea46a89241271cca4fc818d03b32122564623987a5cc0bd3e5a3d1e4c0ed618b9a90eace810d242623e692f4bf9068f4bc594cfb15b15fd6a66190234194f1c8073d7474a1eda2d0336ea831c3c78ce5d505cd14658f7bd428acf7a2f57f80a85418248fb372b47776cfb2c958ad4e14275cdd5d36ed625b4814853373c85a996377a61db606b3385cd3089d2db234c0a4cb970d0f57c6793710f1d345185e99d8bb3d0e0d01837dae599c17fc7333f4c77cdda65022dedc3312514c3749995fac69b4761618f1c285cc95469fa3504dbc62eb4823faabaf8414b5641feddca030c7cda137e2e8b8abc419d98059db3aa28a6c92"}';
//        return response()->json(json_decode($rr,true));

        $http = new Client();
        $input = $request->all();
//        dd(        $input['code']);

        $response = $http->post('https://device.rangstone.com/oauth/token', [
            'form_params' => [
                'code' => $input['code'],
                'grant_type' => 'authorization_code',
                'client_id' => $input['client_id'],
                'client_secret' => $input['client_secret'],
                'redirect_uri' => "https://open.bot.tmall.com/oauth/callback?skillId=5397&token=MzU1ODc1NjI1QUZFSElORkRWUQ==",
            ],
        ]);

        Log::info((string)$response->getBody());

        return response()->json(json_decode((string)$response->getBody(), true));
    }

    //设备发现
    public function handleDiscoveryDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $device1 = ["deviceId" => 'light_01', "deviceName" => '测试灯', "deviceType" => 'light', "brand" => 'sss', "model" => "sss", 'icon' => 'http://www.rangstone.com/upload/201711/1511509063.jpg'];
        $device1['action'] = ["TurnOn", "TurnOff"];
        $device1['properties'] = [['name' => "powerstate", 'value' => "on"], ['name' => "powerstate", 'value' => "off"]];

        $device2 = ["deviceId" => 'qqq', "deviceName" => '测试开关', "deviceType" => 'switch', "brand" => 'sss', "model" => "sss", 'icon' => 'http://www.rangstone.com/upload/201711/1511509063.jpg'];
        $device2['action'] = ["TurnOn", "TurnOff"];
        $device2['properties'] = [['name' => "powerstate", 'value' => "on"], ['name' => "powerstate", 'value' => "off"]];

        $device3 = ["deviceId" => 'tv_1', "deviceName" => '电视', "deviceType" => 'television', "brand" => 'sss', "model" => "sss", 'icon' => 'http://www.rangstone.com/upload/201711/1511509063.jpg'];
        $device3['action'] = ["TurnOn", "TurnOff", "SelectChannel", "AdjustUpChannel", "AdjustDownChannel", "AdjustUpVolume", "AdjustDownVolume", "SetVolume", "SetMute", "CancelMute", "Play", "Pause", "Continue", "Next", "Previous", "SetBrightness", "AdjustUpBrightness", "AdjustDownBrightness"];
        $device3['properties'] = [['name' => "powerstate", 'value' => "on"], ['name' => "powerstate", 'value' => "off"]];

        $device4 = ["deviceId" => 'kongtiao_1', "deviceName" => '空调', "deviceType" => 'aircondition', "brand" => 'sss', "model" => "sss", 'icon' => 'http://www.rangstone.com/upload/201711/1511509063.jpg'];
        $device4['action'] = ["TurnOn", "TurnOff", "SetTemperature", "AdjustUpTemperature", "AdjustDownTemperature", "SetWindSpeed", "AdjustUpWindSpeed", "AdjustDownWindSpeed"];
        $device4['properties'] = [['name' => "powerstate", 'value' => "on"], ['name' => "powerstate", 'value' => "off"]];

        $payload = [];
        $payload['devices'] = [$device1, $device2, $device3, $device4];

        $data['payload'] = $payload;

        Log::info(json_encode($data));

        return response()->json($data);

    }

    //设备打开
    public function handleTurnOnDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));


        if ($payload['deviceId'] == "light_01") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A56G10":[{"cmd":"on"}]}'), 1000);
        }

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G01":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);

    }

    //设备关闭
    public function handleTurnOffDevices(Request $request)
    {
        $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A56G10":[{"cmd":"off"}]}'), 1000);
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "light_01") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A56G10":[{"cmd":"off"}]}'), 1000);
        }

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G02":[{"cmd":"on"}]}'), 1000);
        }


        return response()->json($data);
    }

    //频道切换
    public function handleSelectChannelDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;

        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G03":[{"cmd":"on"}]}'), 1000);
        }


        return response()->json($data);
    }

    //频道增加
    public function handleAdjustUpChannelDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G04":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //频道减少
    public function handleAdjustDownChannelDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G05":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //声音调大
    public function handleAdjustUpVolumeDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G06":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //声音调小
    public function handleAdjustDownVolumeDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G03、7":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //声音调到某个值
    public function handleSetVolumeDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        return response()->json($data);
    }

    //设置静音
    public function handleSetMuteDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));
        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G08":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //取消静音
    public function handleCancelMuteDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G09":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //播放
    public function handlePlayDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G10":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //暂停
    public function handlePauseDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G11":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //继续
    public function handleContinueDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G012":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //下一台
    public function handleNextDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G13":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //上一台
    public function handlePreviousDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G14":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //设置亮度
    public function handleSetBrightnessDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G15":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //调大亮度
    public function handleAdjustUpBrightnessDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));
        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G16":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //调小亮度
    public function handleAdjustDownBrightnessDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "tv_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A61G17":[{"cmd":"on"}]}'), 1000);
        }

        return response()->json($data);
    }

    //设置温度
    public function handleSetTemperatureDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "kongtiao_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A49G01":[{"type":"Aircon"，"tempsensor":"'.$payload['value'].'"}]}'), 1000);
        }

        return response()->json($data);
    }

    //调高温度
    public function handleAdjustUpTemperatureDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "kongtiao_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A49G01":[{"type":"Aircon"，"tempsensor":"32"}]}'), 1000);
        }

        return response()->json($data);
    }

    //调低温度
    public function handleAdjustDownTemperatureDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "kongtiao_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A49G01":[{"type":"Aircon"，"tempsensor":"19"}]}'), 1000);
        }

        return response()->json($data);
    }

    //设置风速
    public function handleSetWindSpeedDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "kongtiao_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A49G01":[{"type":"Aircon"，"fanspeed":"'.$payload['value'].'"}]}'), 1000);
        }

        return response()->json($data);
    }

    //调大风速
    public function handleAdjustUpWindSpeedDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "kongtiao_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A49G01":[{"type":"Aircon"，"fanspeed":"HIGHT"}]}'), 1000);
        }

        return response()->json($data);
    }

    //调小风速
    public function handleAdjustDownWindSpeedDevices(Request $request)
    {
        $data = [];
        $data['header'] = $this->header;
        $payload = $this->payload;


        $data['payload'] = $payload;
        Log::info(json_encode($data));

        if ($payload['deviceId'] == "kongtiao_1") {
            $res = $this->server->sendMessageToDevice('Sdv5hMAlAFx', 'device01', base64_encode('{"A49G01":[{"type":"Aircon"，"fanspeed":"LOW"}]}'), 1000);
        }

        return response()->json($data);
    }

}
